package com.eveningdrum.scriptengine;

import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class JavaScriptEngine {
	private ScriptEngine engine = null;
	public JavaScriptEngine(){
		ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
		//3 ways to get script engine
		//engine = scriptEngineManager.getEngineByName( "javascript" );
		//engine = scriptEngineManager.getEngineByExtension( "js" );
		engine =  scriptEngineManager.getEngineByMimeType( "text/javascript" );
	}
	
	public Object eval( String script ) throws Exception{
		return engine.eval( script );
	}
	public Object eval( CompiledScript cs ) throws Exception{
		if( null == cs )
			return null;
		return cs.eval();
	}
	public CompiledScript compile( String script ) throws Exception{
		CompiledScript cs = null;
		if( engine instanceof Compilable )
			cs = ((Compilable) engine ).compile( script );
		return cs;
	}
}
